﻿using System;
using System.Windows.Threading;
using System.Windows.Navigation;
using System.Collections.ObjectModel;

using Microsoft.Devices;
/*
using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode;
*/
using ZXing;
//using ZXing.Common;
//using ZXing.QrCode;
using Microsoft.Phone.Shell;
using System.Windows;
using Windows.Storage;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.Xml;
using Microsoft.Phone.Tasks;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Shapes;
using System.Threading.Tasks;
using Windows.Phone.Media.Capture;

using Microsoft.Devices;
using Size = Windows.Foundation.Size;



namespace ScannerDemo
{
    public partial class MainPage
    {
       // private ObservableCollection<string> _matches;

        //private PhotoCamera _photoCamera;
        private PhotoCaptureDevice camera;
        
        private PhotoCameraLuminanceSource _luminance;
        private IBarcodeReader _reader;
        private readonly WriteableBitmap _dummyBitmap = new WriteableBitmap(1, 1); 
        
        
        private string resultStr;

        private int width ;
        private int height;

        private string last_result = "";
        private int flag = 0;
        private string last_date;

        private bool camInitflag=true;

        private bool pending = false;

        ApplicationBarIconButton appBarIconBtnRelocation = new ApplicationBarIconButton(new Uri("/icons/home icon.png", UriKind.Relative));

        bool _capturing;
        public delegate void InitializeCameraStart();
        public delegate void InitializeCameraCompleted();//(CameraSensorLocation sensorLocation);
        public delegate void AutoFocusStart();
        public delegate void AutoFocusCompleted();
        public delegate void CaptureCompleted(MemoryStream imageStream);

        public event InitializeCameraStart OnInitializeCameraStart;
        public event InitializeCameraCompleted OnInitializeCameraCompleted;
        public event AutoFocusStart OnAutoFocusStart;
        public event AutoFocusCompleted OnAutoFocusCompleted;
        public event CaptureCompleted OnCaptureCompleted;
        
        public MainPage()
        {            
            InitializeComponent();


            //_matches = new ObservableCollection<string>();
           // _matchesList.ItemsSource = _matches;
            /*
            if (MapAppConfigFileIsExists())
            {
                //不提示pin，将来处理其它事件
               // string config = GetMapAppConfigFile();

            }
            else
            {
                string per = "Yes";//是否允许程序pin.
                if (MessageBox.Show("是否固定功能主页到桌面?", "系统提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {

                    using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream fileStream = file.OpenFile(@"AppConfig.dat", FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            StreamWriter streamWriter = new StreamWriter(fileStream);
                            streamWriter.WriteLine(per);
                            streamWriter.Flush();
                            streamWriter.Dispose();
                            streamWriter.Close();
                        }
                    }
                    Pin2Start();
                }
                else
                {

                    using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        FileStream fileStream = file.CreateFile(@"AppConfig.dat");
                        fileStream.Dispose();
                        fileStream.Close();
                    }
                }

                
            }
             */


        }
        

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // Check to see if the camera is available on the phone.
            _buttonFlash.Visibility = Visibility.Collapsed;
            _buttonLocalImg.Visibility = Visibility.Collapsed;
            _flashText.Visibility = Visibility.Collapsed;
            folderText.Visibility = Visibility.Collapsed;
            bool flashSupported=false;
            try
            {
                if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
                {
                    var SupportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                    if (!e.IsNavigationInitiator&&pending)
                        return;
                    if (camera==null)                 
                        camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, SupportedResolutions[0]);
                    
                    int countFlashMode= PhotoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Back, KnownCameraPhotoProperties.FlashMode).Count();
                    flashSupported = countFlashMode > 1;
                    //IReadOnlyList<object> supportedValues = PhotoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Back, KnownCameraPhotoProperties.FlashMode);
                }
                else if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Front))
                {
                    var SupportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front);
                    camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Front, SupportedResolutions[0]);
                    flashSupported = PhotoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Front, KnownCameraPhotoProperties.FlashMode).Count() > 0;
                }
                else
                {
                    return;
                }

                // Size resolution = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First();

                this.OnAutoFocusCompleted += MainPage_OnAutoFocusCompleted;
                this.OnInitializeCameraCompleted += MainPage_OnInitializeCameraCompleted;
                BarCodeRectInitial();
                Dispatcher.BeginInvoke(() =>
                {

                    if (flashSupported)
                    {
                        _buttonFlash.Visibility = Visibility.Visible;
                        _flashText.Visibility = Visibility.Visible;
                        if (camera!=null)
                            camera.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off);
                    }
                    else
                    {
                        _buttonFlash.Visibility = Visibility.Collapsed;
                        _flashText.Visibility = Visibility.Collapsed;

                    }

                    _buttonLocalImg.Visibility = Visibility.Visible;
                    folderText.Visibility = Visibility.Visible;

                });
                // camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);
                if (camera != null)
                {
                    _previewVideo.SetSource(camera);
                    _previewTransform.Rotation = camera.SensorRotationInDegrees;
                }
                if (OnInitializeCameraCompleted != null)
                    OnInitializeCameraCompleted();
                // KnownCameraGeneralProperties.
                

                

            }
            catch { }
            
            
            base.OnNavigatedTo(e);


            
                
           

        }

        void MainPage_OnInitializeCameraCompleted()
        {
            camInitflag = true;

       
                Dispatcher.BeginInvoke(() => appBarIconBtnRelocation.IsEnabled = true);

                // Disable the flash to avoid reflections
                int width = 640;
                int height = 480;

                try
                {
                    if (camera != null)
                    {

                        width = Convert.ToInt32(camera.PreviewResolution.Width);
                        height = Convert.ToInt32(camera.PreviewResolution.Height);
                       // camera.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashMode.On);
                        /*  if (camera.IsFlashModeSupported(FlashMode.Off))
                          {
                              camera.FlashMode = FlashMode.Off;
                          }
                          if (!camera.IsFlashModeSupported(FlashMode.On))
                          {
                              Dispatcher.BeginInvoke(() =>
                              {
                                  _buttonFlash.Visibility = Visibility.Collapsed;
                                  _buttonLocalImg.Visibility = Visibility.Visible;
                              });
                          }
                          else
                          {
                              Dispatcher.BeginInvoke(() =>
                              {
                                  _buttonFlash.Visibility = Visibility.Visible;
                                  _buttonLocalImg.Visibility = Visibility.Visible;
                              });
                          }
                         * */
                        _luminance = new PhotoCameraLuminanceSource(width, height);
                        _reader = new BarcodeReader(null, bmp => _luminance, null)
                        {
                            AutoRotate = true,
                            TryHarder = false,
                            // PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8 }
                        };
                        _reader.ResultFound += ReaderOnResultFound;
                    }
                }
                catch (ObjectDisposedException ex)
                {
                }





                Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        // camera.Focus();
                        AutoFocus();
                    }
                    catch (Exception ex)
                    {
                    }


                });


        }
        void MainPage_OnAutoFocusCompleted()
        {
            ScanPreviewBuffer();
        }
        /// <summary>
        /// Starts autofocusing, if supported. Capturing buttons are disabled while focusing.
        /// </summary>
        public async Task AutoFocus()
        {
            if (camera != null && !_capturing && PhotoCaptureDevice.IsFocusSupported(camera.SensorLocation))
            {
                if (OnAutoFocusStart != null) OnAutoFocusStart();

                await camera.FocusAsync();

                _capturing = false;

                if (OnAutoFocusCompleted != null) OnAutoFocusCompleted();
            }
        }

       // OnAutoFocusCompleted()
        /*
        private void PhotoCameraOnAutoFocusCompleted(object sender, CameraOperationCompletedEventArgs cameraOperationCompletedEventArgs)
        {
            try
            {
                ScanPreviewBuffer();
            }
            catch (Exception e)
            {
               // MessageBox.Show(e.Message);
            }
        }
        */
        //程序加载预设项目.
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region C#生成ApplicationBar已经相关的Button和事件.
                ApplicationBar = new ApplicationBar();

               
                appBarIconBtnRelocation.Text = "主页";
                appBarIconBtnRelocation.Click += new EventHandler(appBarIconBtnRelocation_Click);
                appBarIconBtnRelocation.IsEnabled = false;
                ApplicationBar.Buttons.Add(appBarIconBtnRelocation);

                /*
                ApplicationBarIconButton appBarIconBtnHistory = new ApplicationBarIconButton(new Uri("/icons/bookmark.png", UriKind.Relative));
                appBarIconBtnHistory.Text = "历史";
                appBarIconBtnHistory.Click += new EventHandler(appBarIconBtnHistory_Click);
                ApplicationBar.Buttons.Add(appBarIconBtnHistory);
                
                ApplicationBarIconButton appBarIconBtnSettings = new ApplicationBarIconButton(new Uri("/icons/appbar.feature.settings.rest.png", UriKind.Relative));
                appBarIconBtnSettings.Text = "设置";
                appBarIconBtnSettings.Click += new EventHandler(appBarIconBtnSettings_Click);
                ApplicationBar.Buttons.Add(appBarIconBtnSettings);
                */
                ApplicationBarMenuItem menuPin2Start = new ApplicationBarMenuItem("固定功能主页到桌面");
                menuPin2Start.Click += new EventHandler(menuPin2Start_Click);
                ApplicationBar.MenuItems.Add(menuPin2Start);

                ApplicationBarMenuItem menuAbout = new ApplicationBarMenuItem("关于");
                menuAbout.Click += new EventHandler(menuAbout_Click);
                ApplicationBar.MenuItems.Add(menuAbout);

                //if (pivotMap.SelectedIndex == 0)
                    ApplicationBar.IsVisible = true;
               // else
               //     ApplicationBar.IsVisible = false;
                ApplicationBar.IsMenuEnabled = true;
                #endregion
              
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void menuAbout_Click(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {

                NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
            });
        }

 
        private void ScanPreviewBuffer()
        {
            try
            {
                if ((_luminance == null)||(camera==null))
                    return;

               // if (_matches.Count > 1) Dispatcher.BeginInvoke(() => _matches.Clear());

                camera.GetPreviewBufferY(_luminance.PreviewBufferY);
                // use a dummy writeable bitmap because the luminance values are written directly to the luminance buffer
                var result = _reader.Decode(_dummyBitmap);

                if (result == null)
                {

                        Dispatcher.BeginInvoke(() => 
                        {
                            try{
                                AutoFocus();
                                //camera.Focus();
                            }catch (Exception e)
                            {
                            }

                            
                        });
                        //Dispatcher.BeginInvoke(() => _matches.Add("No barcode recognized at " + DateTime.Now));
                    }
            }
            catch
            {
            }

        }



        private void  ReaderOnResultFound(Result result)
        {
            // Clear the results

            if (result != null)
            {
                //if (result.BarcodeFormat == BarcodeFormat.EAN_13)
               //     resultStr = "条形码 "+result.Text;
               // else
                    resultStr = result.Text;
                Dispatcher.BeginInvoke(
                    () =>
                    {
                        try
                        {/*
                            if (flag == 0)
                            {
                                last_result = result.Text;
                                flag = 1;
                                String type = "1";
                                write_xml(result.Text, type);
                            }
                            else
                            {
                          */ 
                               // if (result.Text != last_result)
                                //{
                                    String type = "1";
                                    write_xml(resultStr, type);
                                  //  last_result = result.Text;
                              //  }
                            //}
                        }
                        catch (Exception ex)
                        {

                        }

                    });
                NavigateToResult();
            }
            
            try
            {
               // _photoCamera.Focus();
            }
            catch { }
        }
        /*
        private void DisplayResult(string text)
        {
            if(!_matches.Contains(text))
                _matches.Add(text);
            resultStr = text;
            //NavigateUriByLaunchQQBrowser();
        }*/


        //protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
         
        {
            try
            {
                if (camera != null)
                {
                    // Dispose camera to minimize power consumption and to expedite shutdown.
                  //  Dispatcher.BeginInvoke(() =>{
                   // pending = true;
                   // if (camInitflag)
                    //{
                        

                        // Release memory, ensure garbage collection.
                    camera.Dispose();
                    this.OnInitializeCameraCompleted -= MainPage_OnInitializeCameraCompleted;
                    this.OnAutoFocusCompleted -= MainPage_OnAutoFocusCompleted;
                        //_photoCamera.Initialized -= PhotoCameraOnInitialized;
                      //  _photoCamera.AutoFocusCompleted -= PhotoCameraOnAutoFocusCompleted;

                    camera = null;
                    _luminance = null;
                   
                    _reader = null;
                   
                        camInitflag = false;
                        
                        

                    //}
                    //pending = false;
                    if (_reader != null)
                    {
                        _reader.ResultFound -= ReaderOnResultFound;
                        _reader = null;
                    }
                    //_reader.ResultPointFound
                   // });
                }
            }
            catch { }
            
            base.OnNavigatedFrom(e);

        }

        // Update the UI if initialization succeeds.
        void PhotoCameraOnInitialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
        {
            camInitflag = true;
            
            if (e.Succeeded)
            {
                Dispatcher.BeginInvoke(() => appBarIconBtnRelocation.IsEnabled = true);

                // Disable the flash to avoid reflections
                int width = 640;
                int height = 480;

                try
                {
                    if (camera != null)
                    {

                        width = Convert.ToInt32(camera.PreviewResolution.Width);
                        height = Convert.ToInt32(camera.PreviewResolution.Height);
                      /*  if (camera.IsFlashModeSupported(FlashMode.Off))
                        {
                            camera.FlashMode = FlashMode.Off;
                        }
                        if (!camera.IsFlashModeSupported(FlashMode.On))
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                _buttonFlash.Visibility = Visibility.Collapsed;
                                _buttonLocalImg.Visibility = Visibility.Visible;
                            });
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                _buttonFlash.Visibility = Visibility.Visible;
                                _buttonLocalImg.Visibility = Visibility.Visible;
                            });
                        }
                       * */
                        _luminance = new PhotoCameraLuminanceSource(width, height);
                        _reader = new BarcodeReader(null, bmp => _luminance, null)
                        {
                            AutoRotate = true,
                            TryHarder = false,
                           // PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8 }
                        };
                        _reader.ResultFound += ReaderOnResultFound;
                    }
                }
                catch (ObjectDisposedException ex) 
                {
                }





                Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                       // camera.Focus();
                    }
                    catch (Exception ex)
                    {
                    }


                });

            }
            else
            {
            }
        }

        async void NavigateUriByLaunchNokiaBrowser()
        {

            string uriString = "nokiabrowser2:" + resultStr;
            Uri uri = new Uri(uriString);
            
            try
            {
                bool success = await Windows.System.Launcher.LaunchUriAsync(uri);
                if (success)
                {
                    // URI launched
                }
                else
                {
                    // URI launch failed
                }
            }
            catch
            { }
        }

        //浏览
        async public void NavigateToResult()
        {
            try
            {
                BarCodeRectSuccess();
                if (camera != null)
                {
                    camera.Dispose();
                    camera = null;
                }
                if (resultStr.Contains("BEGIN:VCARD"))
                {
                    string fileName = "temp2open.vcf";
                    Vcard vcard = new Vcard();
                    await vcard.WriteFile(fileName, resultStr);
                    await DefaultLaunch(fileName);
                    pending = false;
                }
                else 
                {
                    //NavigateUriByLaunchNokiaBrowser();
                    Dispatcher.BeginInvoke(() =>
                        {
                            App.PublicText = resultStr;
                            NavigationService.Navigate(new Uri("/ScanResult.xaml" , UriKind.Relative));
                        });
                    
                }
            }
            catch { }
            //pending = false;

        }
        //appBarIconBtnRelocation
        void appBarIconBtnRelocation_Click(object sender, EventArgs e)
        {

                //_photoCamera.Focus();
               // _photoCamera.FocusAtPoint(0.5, 0.5);
            //_timer.Stop();

            //string url_item = "1:";
            //string uriString = @"/ScannerDemo;component/HomePagePivot.xaml?text=" + url_item;
            //NavigationService.Navigate(new Uri(uriString, UriKind.RelativeOrAbsolute));
            NavigationService.Navigate(new Uri("/HomePagePivot.xaml", UriKind.Relative));
      
            
        }

        void appBarIconBtnHistory_Click(object sender, EventArgs e)
        {
            

        }
        
        private void _matchesList_KeyDown_1(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //Uri uri = new Uri("nokiabrowser:http://3g.163.com&nbopentype=1&nbtrans=1");//new Uri("nokiabrowser:http://3g.163.com&nbopentype=1&nbtrans=1&nbcallername=launcher");
        }
        /*
        private void CamAutoFocus()
        {
            if (_skipFrames++ > SkipedFramesMax)
            {
                try
                {
                    _photoCamera.Focus();
                }
                catch
                { }
                _skipFrames = 0;
            }
        }*/
        async Task DefaultLaunch(string fileName)
        {

            // Path to the file in the app package to launch

           // string fileName = @"test.vcf";
            bool success = false;

            IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
            IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);

            //var storageFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileName);



            if (storageFile != null)
            {
               // pending = true;
                success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
               // pending = false;

                



                if (success)
                {

                    // File launched

                }

                else
                {

                    // File launch failed

                }

            }

            else
            {

                // Could not find file

            }

        }

        //add new scanner results to the history file of xml.
        public void write_xml(String text,String type)
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            if (file.FileExists("re.xml"))
            {
                add_to_xml(text,type);
                //file.DeleteFile("re.xml");
            }
            else
            {
                create_xml(text,type);
            }
        }

        //If there isn't a xml file named "result.xml",then create one.
        /*xml format
         * 
         <results>
             <id>1</id>
         *   <result>
         *       <date>2012/9/2</date>
         *       <result_item>
         *           <min>19:24</min>
         *           <type>网址</type>
         *           <text>http://</text>
         *           <id>1</id>
         *           <total_text>http://</total_text>
         *       </result_item>
         *   </result>
         </results>
         */
        protected void create_xml(String text,String type)
        {
            using (var myFileStream = new IsolatedStorageFileStream("re.xml", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
            using (var writer = new StreamWriter(myFileStream))
            {
                XElement root = XElement.Parse(@"
<results>
<id>1</id>
</results>
");
                //XElement r = root.Element("results");
                int i = 1;
                root.Add(new XElement("result", new XElement("date", get_date()), new XElement("result_item", new XElement("min", get_min()), new XElement("type", get_type(text)), new XElement("text", text), new XElement("id", i), new XElement("generate_type", type))));
                root.Save(writer);
                writer.Close();
            }
        }

        //If there is a xml,then add scan result to the xml file.
        void add_to_xml(String text,String type)
        {
            XElement root;
            using (var myFileStream = new IsolatedStorageFileStream("re.xml", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
            using (var reader = new StreamReader(myFileStream))
            {
                root = XElement.Load(reader);
                string i = root.Element("id").Value.ToString();
                int j = System.Int32.Parse(i);
                try
                {
                    j += 1;
                }
                catch {
                    j = 1;
                }
                string k = j.ToString();
                root.Element("id").ReplaceWith(new XElement("id",k));
                //XElement root = XElement.Parse(reader.ReadToEnd());

           // XElement root = XElement.Load("history.xml");
                IEnumerable<XElement> searchDate =
                    from el in root.Elements("result")
                    where (string)el.Element("date") == get_date()
                    select el;
                bool searchFlag = false;

                int count = 0;
                try
                {
                    IEnumerable<XElement> countDate =
        from el in root.Elements("result").Elements("result_item").OrderBy(element => System.Int32.Parse(element.Element("id").Value))
        select el;

                    count = countDate.Count();
                    if (count > 50)//如果大于50个记录则删除id号最小的记录。
                    {
                        /*
                        foreach (var temp in countDate)
                        {
                        }*/
                        string delId = countDate.First().Element("id").Value.ToString();
                        //var delId = countDate.Elements("id").Min(element => (string)element.Value.ToString());
                        foreach (var item_result in root.Elements("result"))
                        {
                            foreach (var item_result_item in item_result.Elements("result_item"))
                            {
                                if (item_result_item.Element("id").Value.ToString() == delId)
                                {
                                    if (item_result.Nodes().Count() == 2)
                                    {
                                        item_result.Remove();
                                    }
                                    else
                                    {
                                        item_result_item.Remove();
                                        //MessageBox.Show(root.ToString());

                                    }
                                }
                            }
                        }
                    }
                }
                catch
                { }

                


               
                foreach (XElement el in searchDate)
                    {
                        searchFlag = true;
                        
                        el.Element("date").AddAfterSelf(new XElement("result_item", new XElement("min", get_min()), new XElement("type", get_type(text)), new XElement("text", text), new XElement("id", j), new XElement("generate_type", type)));
                        break;
                    }
                if (!searchFlag)
                {
                   // root.add(new XElement("result", new XElement("date", get_date()), new XElement("result_item", new XElement("min", get_min()), new XElement("type", get_type(text)), new XElement("text", text), new XElement("id", j), new XElement("generate_type", type))));
                    root.Element("id").AddAfterSelf(new XElement("result", new XElement("date", get_date()), new XElement("result_item", new XElement("min", get_min()), new XElement("type", get_type(text)), new XElement("text", text), new XElement("id", j), new XElement("generate_type", type))));
                }
              
               root.Elements("result").OrderBy(element => (string)element.Element("date"));
               List<XElement> ordered = root.Elements("result")
   .OrderByDescending(element => (string)element.Element("date"))
   .ToList();
               foreach (var old in ordered)
                   old.Remove();
                //foreach (var new int ordered)
                
               root.Add(ordered);
                /*
                XElement r = root.Element("result").Element("date");
                last_date = get_last_date(root);
                if (last_date != get_date())
                {
                    root.Add(new XElement("result", new XElement("date", get_date()), new XElement("result_item", new XElement("min", get_min()), new XElement("type", get_type(text)), new XElement("text", text), new XElement("id", j), new XElement("generate_type", type))));
                    last_date = get_date();
                    //r.AddAfterSelf(new XElement("AddDate", DateTime.Now));
                }
                else
                {
                    r.AddAfterSelf(new XElement("result_item", new XElement("min", get_min()), new XElement("type", get_type(text)), new XElement("text", text), new XElement("id", j), new XElement("generate_type", type)));
                }
                 * */
               reader.Close();
            }
            using (var myFileStream = new IsolatedStorageFileStream("re.xml", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
            using (var writer = new StreamWriter(myFileStream))
            {
                root.Save(writer,SaveOptions.DisableFormatting);
                writer.Close();
            }
        }

        String get_date()
        {

           // return DateTime.Now.Date.ToString().Substring(0, 8);
            string currentDate=DateTime.Now.Date.ToString("yyyy/MM/dd");
            return currentDate;
            //2013/6/1
        }

        String get_min()
        {
            return DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00");
        }

        String get_type(String text)
        {
            /*
            if (text.Length >= 7)
            {
                if (text.Substring(0, 7) == "http://")
                {
                    return "网址";
                }
                else if (text.Substring(0, 11) == "BEGIN:VCARD")
                {
                    return "名片";
                }
                else
                {
                    return "文本";
                }
            }
            else
            {
                return "文本";
            }
             * */
            return common.CommonLib.get_type(text);

        }

        String get_last_date(XElement root)
        {
            XNode FirstNode = root.FirstNode.NextNode;
            XElement result2 = XElement.Load(FirstNode.CreateReader());

            return result2.Element("date").Value;
        }

        private void Button_Click_Flash(object sender, RoutedEventArgs e)
        {

            try
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        var temp = camera.GetProperty(KnownCameraPhotoProperties.FlashMode);
                        if (System.Int32.Parse(camera.GetProperty(KnownCameraPhotoProperties.FlashMode).ToString()) == 0)
                        {
                            camera.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.On);
                            _flashText.Text = "开";
                            //ImageSource imgsrc1 = new BitmapImage(new Uri("/Assets/AppBar/Flashlight.png", UriKind.RelativeOrAbsolute));
                           // _flashImg.Source = imgsrc1;
                        }
                        else
                        {
                            camera.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off);
                            _flashText.Text = "关";
                            //ImageSource imgsrc1 = new BitmapImage(new Uri("/Assets/AppBar/folder.png", UriKind.RelativeOrAbsolute));
                           // _flashImg.Source = imgsrc1;

                        }
                    });
                /*
                 * Off = 0,  Auto = 1,  On = 3,
                if (_photoCamera.IsFlashModeSupported(FlashMode.Off))
                {
                    if (_photoCamera.FlashMode == FlashMode.Off)
                        _photoCamera.FlashMode = FlashMode.On;
                    else
                        _photoCamera.FlashMode = FlashMode.Off;
                }*/
            }
            catch { }
        }

        private void Button_Click_LocalMedia(object sender, RoutedEventArgs e)
        {
            try
            {
                PhotoChooserTask choosePhoto = new PhotoChooserTask();

                choosePhoto.Completed += choose_photo_Completed;
                
                choosePhoto.PixelHeight = 400;
                choosePhoto.PixelWidth = 400;
                choosePhoto.ShowCamera = true;
                
                //pending = true;
                choosePhoto.Show();
            }
            catch { }
        }
        void choose_photo_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                var bit_map = new BitmapImage();
                bit_map.SetSource(e.ChosenPhoto);
                WriteableBitmap writer_able_bitmap = new WriteableBitmap(bit_map);
                /* LuminanceSource source = new ZXing.RGBLuminanceSource();RGBLuminanceSource(writer_able_bitmap, writer_able_bitmap.PixelWidth, writer_able_bitmap.PixelHeight);
                 ZXing.RGBLuminanceSource
                 var binarizer = new HybridBinarizer(source);
                 var binBitmap = new BinaryBitmap(binarizer);*/
                var _localReader = new BarcodeReader();
                var result = _localReader.Decode(writer_able_bitmap);
                

                if (result != null)
                {
                    pending = true;
                    ReaderOnResultFound(result);
                }
                else
                {
                  Dispatcher.BeginInvoke(() =>
                    {
                    MessageBox.Show("未能识别此图片！");
                    });
                    pending = false;
                }
            }else
                pending = false;
            
            
        }

        //重写返回事件-退出程序
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            e.Cancel = true;
            Dispatcher.BeginInvoke(() =>
            {
                if ((camInitflag == false) || (MessageBox.Show("确定要退出吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel))
                    e.Cancel = true;
                else
                    Application.Current.Terminate();
            });

                 //   base.OnBackKeyPress(e);
        }

        /// <summary>
        /// Event handler for when the checkbox is checked. Create a secondary tile if it doesn't
        /// already exist.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuPin2Start_Click(object sender, EventArgs e)
        {
            Pin2Start();

        }

        public void Pin2Start()
        {
            // Look to see if the tile already exists and if so, don't try to create again.
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("Home"));

            //IEnumerable<ShellTile> 
            List<ShellTile> tiles = ShellTile.ActiveTiles.ToList();
            

            // Create the tile if we didn't find it already exists.
            if (TileToFind == null)
            {
                // Create the tile object and set some initial properties for the tile.
                // The Count value of 12 will show the number 12 on the front of the Tile. Valid values are 1-99.
                // A Count value of 0 will indicate that the Count should not be displayed.
                StandardTileData NewTileData = new StandardTileData
                {
                    BackgroundImage = new Uri("Background.png", UriKind.Relative),
                    Title = "诺基亚扫天下 功能页",
                    //Count = 12,
                    //BackTitle = "背面",
                    //BackContent = "背面内容",
                    //BackBackgroundImage = new Uri("Blue.jpg", UriKind.Relative)
                };

                // Create the tile and pin it to Start. This will cause a navigation to Start and a deactivation of our application.
                ShellTile.Create(new Uri("/HomePagePivot.xaml?from=Tile", UriKind.Relative), NewTileData);
            }
            else
            {
                MessageBox.Show("您已经固定到桌面了");
            }
        }

        /// <summary>
        /// 判断软件的配置文件是否存在
        /// </summary>
        /// <returns>返回是否存在</returns>
        public bool MapAppConfigFileIsExists()
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                return file.FileExists(@"AppConfig.dat");
            }
        }
        /// <summary>
        /// 读取软件记录的客户端程序
        /// </summary>
        /// <returns>返回程序配置信息.如果不存在配置文件.则返回的是默认的配置信息</returns>
        public string GetMapAppConfigFile()
        {
            string strMapAppConfig = "No|0";
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = file.OpenFile(@"AppConfig.dat", FileMode.Open, FileAccess.Read))
                {
                    StreamReader streamReader = new StreamReader(fileStream);
                    strMapAppConfig = streamReader.ReadLine();
                    streamReader.Close();
                }
            }
            return strMapAppConfig;
        }
        void BarCodeRectSuccess()
        {
            Dispatcher.BeginInvoke(() =>
            {
                _marker1.Fill = new SolidColorBrush(Colors.Green);
                _marker2.Fill = new SolidColorBrush(Colors.Green);
                _marker3.Fill = new SolidColorBrush(Colors.Green);
                _marker4.Fill = new SolidColorBrush(Colors.Green);
                _marker5.Fill = new SolidColorBrush(Colors.Green);
                _marker6.Fill = new SolidColorBrush(Colors.Green);
                _marker7.Fill = new SolidColorBrush(Colors.Green);
                _marker8.Fill = new SolidColorBrush(Colors.Green);
                progressBar.IsIndeterminate = false;
            });
        }


        void BarCodeRectInitial()
        {
           Dispatcher.BeginInvoke(() =>
            {
            _marker1.Fill = new SolidColorBrush(Colors.Red);
            _marker2.Fill = new SolidColorBrush(Colors.Red);
            _marker3.Fill = new SolidColorBrush(Colors.Red);
            _marker4.Fill = new SolidColorBrush(Colors.Red);
            _marker5.Fill = new SolidColorBrush(Colors.Red);
            _marker6.Fill = new SolidColorBrush(Colors.Red);
            _marker7.Fill = new SolidColorBrush(Colors.Red);
            _marker8.Fill = new SolidColorBrush(Colors.Red);
            progressBar.IsIndeterminate = true;
            appBarIconBtnRelocation.IsEnabled = false;
            });
        }
    


      }
}